//
//  HMOAuthViewController.swift
//  微博
//
//  Created by 程双岐 on 16/9/21.
//  Copyright © 2016年 heima. All rights reserved.
//
/*
 App Key：4212101591
 App Secret：6b8fc6b8f06414d3378303e1294cda02
 
 https://api.weibo.com/oauth2/authorize?client_id=4212101591&redirect_uri=http://www.baidu.com/response&response_type=code
 
 https://api.weibo.com/oauth2/authorize?client_id=4212101591&redirect_uri=http://www.oschina.net
 /response&response_type=code
 */

import UIKit
import SVProgressHUD

let key = "4212101591"

let https = "http://www.oschina.net"

let WeiboAppSecret = "6b8fc6b8f06414d3378303e1294cda02"




class HMOAuthViewController: UIViewController {

    private lazy var webView : UIWebView = UIWebView()
    
    
    override func loadView() {
      super.loadView()
        webView.isOpaque = false
        
        webView.delegate = self
        
        view = webView
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        requsetLogin()
        setupUI()
    }

    private func requsetLogin (){
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(key)&redirect_uri=\(https)"
        
        let requset = URLRequest(url: URL(string : url)!)
        
        webView.loadRequest(requset)
        
    }
    
    private func setupUI(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(dismissAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(tiaoChongAcrion))
        
    }
    
    @objc private func dismissAction(){
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func tiaoChongAcrion(){
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '13199030306';document.getElementById('passwd').value = 'csq123654'")
    }

    
}

extension HMOAuthViewController: UIWebViewDelegate{

    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.url else {
            print("url错误")
            return false
        }
        if !url.absoluteString.hasPrefix(https) {
            print("不是我要的url")
            return true
        }
        
        if let query = url.query ,query.hasPrefix("code=") {
            
            let code = query.substring(from: "code=".endIndex)
            
            HMUserAccpuntViewModel.sharedUserAccountViewModel.requsetAccessToken(code: code, callBack: { (succeed) in
                if succeed {
                    print("登录成功")
                    self.dismiss(animated: false, completion: { 
                        NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotification), object: self)
                    })
                }
            })
            
        }else{
            //MARK: 点击取消授权时进行disminss
            SVProgressHUD.dismiss()
            dismiss(animated: true, completion: nil)
        }
        
        return false
    }

}

